package net.qiqbframework.eventhandling.distributing;

import lombok.extern.slf4j.Slf4j;
import net.qiqbframework.eventhandling.EventMessage;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 分发事件
 */
@Slf4j
public class DefaultEventDistributor implements EventDistributor {

    private final ExecutorService executorService;

    private EventChannel eventChannel;
    /**
     * 延迟任务，key：聚合ID，value ，代发事件
     */
    private final BlockingQueue<EventMessage<?>> delayedTasks = new LinkedBlockingQueue<>();

    public DefaultEventDistributor(Builder builder) {
        this.eventChannel = builder.eventChannel;
        this.executorService = Executors.newFixedThreadPool(100);

    }

    public void distributing(EventMessage<?> eventMessage) {
        // delayedTasks.offer(eventMessage);
        executorService.submit(() -> {
            log.info("发送消息{}", eventMessage.getIdentifier());
            doDistributing(eventMessage);
        });
    }

    public void doDistributing(EventMessage<?> eventMessage) {
        eventChannel.sendEventMessage(eventMessage);
    }


    public static class Builder {
        private EventChannel eventChannel;

        public Builder eventChannel(EventChannel eventChannel) {
            this.eventChannel = eventChannel;
            return this;
        }

        public DefaultEventDistributor build() {
            return new DefaultEventDistributor(this);
        }
    }
}
